package cn.szsys.integration.runner;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.szsys.integration.constants.AppConstant;
import cn.szsys.integration.runner.entity.AuthorizationConfig;
import cn.szsys.integration.util.OkHttpUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;

/**
 * @author Ryan
 * @since 2025-05-08
 **/
@Component
@Slf4j
public class LoadDownstreamRunner implements CommandLineRunner {

    @Value("${sys.global.auth.authorization-file:classpath:authorization.json}")
    private String authorizationFile;
    @Resource
    private ConfigurableEnvironment environment;

    @Override
    public void run(String... args) throws Exception {
        OkHttpUtil.builder();
    }

    /**
     * 读取授权文件
     * @author Ryan
     */
    private void loadAuthorization()  throws Exception {
        log.info("开始读取授权文件：{}", authorizationFile);
        try (BufferedReader reader = ResourceUtil.getReader(authorizationFile, StandardCharsets.UTF_8);) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            AuthorizationConfig authorizationConfig = JSON.parseObject(content.toString(), AuthorizationConfig.class);
            authorizationConfig.initAkMap();

            // 将参数添加到 Environment 中
            environment.getSystemProperties().put(AppConstant.DOWNSTREAM_CONFIGURATION, authorizationConfig);
        } catch (Exception e) {
            log.error("读取授权文件出错！", e);
            throw e;
        }
    }
}
